package com.cneport.das.server.trans.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author GavinZhang
 * @version 1.0
 * @desc： 主动拉取消息的频率保护
 * @company 东方物通科技有限（北京）公司
 * @date 2021/9/2 11:41
 */
@Component
public class ReceiveProtect {

    @Autowired
    private PropertiesReader propertiesReader;

    private final Map<String, Long> senderFrequency = new ConcurrentHashMap<>();

    public boolean pass(String flagId) {
        int need = propertiesReader.getPullProtect();
        //需要保护
        if (need == 1) {
            long internal = propertiesReader.getInternalMillis();
            Long last = senderFrequency.get(flagId);
            Long now = System.currentTimeMillis();
            if (last == null) {
                senderFrequency.put(flagId, now);
                return true;
            } else {
                if (now - last.longValue() > internal) {
                    senderFrequency.put(flagId, now);
                    return true;
                } else {
                    return false;
                }
            }
        } else {
            //不需要保护
            return true;
        }
    }
}
